import {Component, HostBinding, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {AuthService} from '../../../service/auth.service';
import {MatDialog, MatSnackBar} from '@angular/material';
import {errorSnackBar, openSnackBar} from '../../../util/snack.util';
import {alertDialog, loadingDialog} from '../../../util/dialog.util';
import {CaptchaComponent} from '../captcha.component';
import {ConfigService} from '../../../service/config.service';
import {slideToTop} from '../../../anim/router.anim';

@Component({
  selector: 'app-recover',
  templateUrl: './recover.component.html',
  styleUrls: ['./recover.component.css'],
  animations: [slideToTop]
})
export class RecoverComponent extends CaptchaComponent implements OnInit {
  @HostBinding('@routeAnim') routeAnim;

  constructor(private fb: FormBuilder,
              public snackBar: MatSnackBar, private dialog: MatDialog,
              public configService: ConfigService, public authService: AuthService) {
    super(snackBar, configService, authService);
    this.formModel = fb.group({
      email: ['', [Validators.required, Validators.email,
        Validators.minLength(6), Validators.maxLength(255)]],
      captcha: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.changeCaptcha();
  }

  onSubmit() {
    if (this.formModel.valid) {
      const loadingDialogRef = loadingDialog(this.dialog);
      this.authService.sendResetPassEmail(
        this.formModel.get('email').value,
        this.formModel.get('captcha').value)
        .subscribe(result => {
          loadingDialogRef.close();
          alertDialog(this.dialog, '成功', '重置密码邮件已发送，需要你手动到邮箱（可能在垃圾箱哦 (；′⌒`) ）点击链接重置密码');
        }, error1 => {
          loadingDialogRef.close();
          errorSnackBar(this.snackBar, error1);
          this.changeCaptcha();
        });
    } else {
      openSnackBar(this.snackBar, '请检查是否符合所有填写规则');
    }
  }
}
